package com.zy.demo048084.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

// sentinel异常处理
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setStatus(429);
        PrintWriter out = response.getWriter();
        String msg = "";
        String url = "";
        if (e instanceof FlowException) {
            msg += "Flow Exception";
            url = "http://baidu.com";
        } else if (e instanceof DegradeException) {
            msg += "Degrade Exception";
            url = "http://baidu.com";
        } else if (e instanceof SystemBlockException) {
            msg += "System Block Exception";
            url = "http://baidu.com";
        } else if (e instanceof ParamFlowException) {
            msg += "Param Flow Exception";
            url = "http://baidu.com";
        } else if (e instanceof AuthorityException) {
            msg += "Authority Exception";
            url = "http://baidu.com";
            response.setStatus(401);
        }
//        返回流格式
//        out.println(msg);
//        out.flush();
//        out.close();
        response.sendRedirect(url);
    }
}
